Mini curso: Quarto y GitHub Pages

III Jornadas de Ingeniería Estadística 2024
11 y 12 de Noviembre 2024, Auditorio DMCC
Universidad de Santiago de Chile
Logo JIE

Francisco Plaza Vega

USACH

Introducción

¿Qué es la Investigación Reproducible?

Es la práctica de conducir estudios científicos o basados en datos de tal manera que permita a otros replicar o reproducir los resultados usando los mismos datos, códigos y metodologías.

Etapas de una Investigación Reproducible

Ciencia Abierta

Espectro de Reproducibilidad

Qué necesitaremos?

Repositorio

Enlaces importantes

Sofware necesarios

R project

https://cran.dcc.uchile.cl/

RSudio IDE

https://posit.co/download/rstudio-desktop/

Existen otras alternativas más génericas como Visual Studio Code, un editor de código para múltiples lenguajes. Sin embargo, al no ser un software especializado en R, requiere utilizar extensiones para lograr las funcionalidad que otorga RStudio.

Quarto

https://quarto.org/docs/get-started/

Git & Github

Quarto

Rmarkdown & Quarto

El paquete rmarkdown provee un marco de escritura para investigaciones cuentitativas, que combina códigos, resultados y texto. Los documento R Markdown son completamente reproducibles y permiten generar archivos en distintos formatos: PDF, Word, Presentaciones y más. Quarto es la nueva generación de esta herramienta para incluir distintos lenguajes.

Algunos ejemplos

Quarto

Los archivos Quarto fueron diseñados para ser usados de tres maneras:

  1. Para comunicar a los tomadores de decisiones, quienes quieren centrarse en las conclusiones, no en el código detrás del análisis.

  2. Para colaborar con otros investigadores, quienes están interesados en las conclusiones y el cómo se llego a ellas (i.e. el código)

  3. Como un ambiente para hacer análisis, como un notebook donde se puede capturar el trabajo realizado junto a notas de este.

Primeros pasos

  1. Entrar a Quarto.org
  2. Descargar Quarto para tu sistema operativo
  3. Ingresar a RStudio y crear documento .qmd

Flujo documento Quarto

  • qmd: archivo de origen
  • knitr: Herramienta que interpreta y ejecuta códigos y lo traduce en texto markdown
  • md: texto escrito en lenguaje markdown
  • pandoc: Herramienta que convierte archivos .md enb distintos formatos

Anatomía de un documento Quarto

  1. Encabezado en formato YAML
  2. Texto en formato Quarto
  3. Bloques de código (R, Python, Julia, Observable)

YAML

YAML es un formato de serialización de datos que puede ser leído fácilmente. Su uso es amplio, desde Acciones en GitHub hasta Quarto

Un ejemplo de YAML que difine un ambiente computacional podría ser:

# Define the operating system as Linux
os: linux

# Use the xenial distribution of Linux
dist: xenial

# Use the programming language Python
language: python

# Use version of Python 3.2
python: 3.2

YAML nos será de particular interés para la creación de documentos y presentaciones reproducibles, utilizando quarto.

Herramientas

El contenido del documento puede estar escrito utilizando diferentes formatos, entre ellos:

  • Quarto
  • HTML
  • LaTeX
  • CSS

Creación de documento básico

  1. Abrir RStudio
  2. File > New File > Quarto Document
  3. Definir características del documento

Markdown

Formato de Texto

Sintáxis Markdown Salida
*italics*, **bold**, ***bold italics***
italics, bold, bold italics
superscript^2^ / subscript~2~
superscript2 / subscript2
~~strikethrough~~
strikethrough
`verbatim code`
verbatim code

Encabezados

Sintáxis Markdown Salida
# Header 1

Header 1

## Header 2

Header 2

### Header 3

Header 3

#### Header 4

Header 4

##### Header 5
Header 5
###### Header 6
Header 6

Listas

Sintáxis Markdown Salida
* Lista no ordenada
    + sub-item 1
    + sub-item 2
        - sub-sub-item 1
  • Lista no ordenada
    • sub-item 1
    • sub-item 2
      • sub-sub-item 1
*   item 2

    Continuación (4 spaces)
  • item 2

    Continuación (4 spaces)

1. Lista ordenada
2. item 2
    i) sub-item 1
         A.  sub-sub-item 1
  1. Lista ordenada
  2. item 2
    1. sub-item 1
      1. sub-sub-item 1

Listas

(@)  Una lista cuyos números

continuan después

(@)  de una interrupción
  1. Una lista cuyos números

continuan después

  1. de una interrupción
::: {}
1. Una lista
:::

::: {}
1. Seguida de otra lista
:::
  1. Una lista
  1. Seguida de otra lista
término
: definición
término

definición

Tablas

Sintáxis Markdown

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |

Output

Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1

Código de fuente

Usamos ``` para delimitar bloques de código:

```
código
```

Podemos agregar un lenguaje para destacar el código:

```python
1 + 1
```

Pandoc ofrece 140 distintos lenguajes para destacar código.

Guía de referencia

Para una lista exhaustiva de las opciones de formato que tienen los documentos .qmd visitar https://quarto.org/docs/guide/.

Formatos de salida: Documentos

Los formatos de salida más utilizados para documentos creados con Quarto son:

Para cambiar entre estos formatos, basta especificiar la salida deseada en el YAML. Otros formatos posibles:

Formatos de salida: Presentaciones

En Quarto tenemos 3 opciones para presentaciones:

En donde RevealJS es el formato que nos entrega más herramientas. (Esta presentación fue hecha utilizando RevealJS en Quarto)

Caso práctico

Crearemos un mismo documento en distintos formatos

Awesome Quarto

Templates

Este tutorial

Este tutorial usa un template llamado clean. Está disponible en un repositorio en GitHub.

Other stuff

Example slide

This is a subtitle

Before we dive a bit deeper, here is a simple example of the clean theme in action.

  • No pictures or anything fancy. Just text for the moment.

Next, we’ll take a brief tour of some theme components.

  • We’ll use the same basic structure as the original LaTeX slides.
  • Note that the full suite of Reveal.js features are available for this Quarto implementation, even if we don’t cover everything here.

Before you proceed…

Requirements for the coding examples in this demo

The clean theme is language agnostic. Use it with R, Python, Julia, etc. Or none of the above.

However, this demo uses R code to highlight advanced theme features. You’ll need to install some software if you’d like to render the demo “as-is”.

Required software (this demo only)

R packages

install.packages(c("modelsummary", "fixest", "pdftools", "tinytex", "threejs"))

TinyTex

quarto install tinytex

While reveal.js presentations are HTML format, we will show an example of how to embed LaTeX tables as images. This requires a working Tex distribution, of which TinyTex provides by far the easiest and lightest integration with Quarto. More details here.

Components

Components

Ordered and Unordered Lists

Here we have an unordered list.

  • first item
    • sub-item
  • second item

And next we have an ordered one.

  1. first item
    1. sub-item
  2. second item

Components

Alerts & Cross-refs

To emphasize specific words or text, you can:

  • Use the default .alert class, e.g. important note.
  • Use the .fg class for custom colour, e.g. important note.
  • Use the .bg class for custom background, e.g. important note.

To cross-reference, you have several options, for example:

  • Beamer-like .button class provided by this theme, e.g. Appendix
  • Quarto’s native cross-ref syntax, e.g., “See Sección 15.3.”

Components

Citations

Citations follow the standard Quarto format and be sourced from BibLaTex, BibTeX, or CLS files. For example:

Components

Blocks

Quarto provides dedicated environments for theorems, lemmas, and so forth.

But in presentation format, it’s arguably more effective just to use a Callout Block.

Regression Specification

The main specification is as follows:

\[ y_{it} = X_{it} \beta + \mu_i + \varepsilon_{it} \]

Components

Multicolumn I: Text only

Column 1

Here is a long sentence that will wrap onto the next line as it hits the column width, and continue this way until it stops.

Column 2

Some other text in another column.

A second paragraph.

Multicolumn support is very flexible and we can continue with a single full span column in the same slide.

Components

Multicolumn II: Text and figures

  • A point about the figure that is potentially important.
  • Another point about the figure that is also potentially important.

Note that sub- and multi-panel figures are also natively supported by Quarto. See here.

Components

Multicolumn III: Code and output

palette("Classic Tableau")

par(
  family = "HersheySans",
  las = 1, pch = 19, cex = 1.5
)

pairs(
  iris[,1:4],
  col=iris$Species
)
Figura 1: Pairwise scatterplot

Tables

Markdown tables

Default table styling

The clean theme rolls its own minimalist aesthetic for tables. This should interface directly with Quarto’s excellent table support.

| fruit  | price  |
|--------|-------:|
| apple  | 2.05   |
| pear   | 1.37   |
| orange | 3.09   |

: Fruit prices {tbl-colwidths="[75,25]"}
Fruit prices
fruit price
apple 2.05
pear 1.37
orange 3.09

Regression tables

Regression example

These aesthetics should carry over to any computation-based tables too.

Let’s take a few slides to illustrate via a simple regression example:

library(fixest)

mods = feols(
  rating ~ complaints + privileges + learning + csw0(raises + critical),
  data = attitude
)

dict = c("rating"     = "Overall Rating",
         "complaints" = "Handling of Complaints",
         "privileges" = "No Special Priviledges",
         "learning"   = "Opportunity to Learn",
         "raises"     = "Performance-Based Raises",
         "critical"   = "Too Critical")

Regression tables

modelsummary

Popular regression table software should play nicely with this theme out of the box. Here’s an example using modelsummary (with the default tinytable backend1). See the next slide for the resulting table.

library(modelsummary) # Make sure you have >=v2.0.0

modelsummary(
  setNames(mods, c("(1)", "(2)")),
  coef_map = dict, stars = TRUE,
  gof_map = NA
  ) |>
  # some optional stylistic tweaks
  tinytable::group_tt(j = list("Dep. variable: Overall Rating" = 2:3)) |>
  tinytable::style_tt(i = 1:2, j = 2:3, background = "pink")

Regression tables

Dep. variable: Overall Rating
(1) (2)
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001
Handling of Complaints 0.682*** 0.692***
(0.129) (0.149)
No Special Priviledges -0.103 -0.104
(0.129) (0.135)
Opportunity to Learn 0.238+ 0.249
(0.139) (0.160)
Performance-Based Raises -0.033
(0.202)
Too Critical 0.015
(0.147)

Regression tables

fixest::etable

Aside: We used the fantastic fixest package to estimate our regression models. fixest bundles its own powerful tabling functions. These were designed for LaTeX output, but can work with this (HTML) theme too.1

  • Set the output: asis R chunk option in your Quarto doc.
  • Set the markdown = TRUE fixest::etable option.
```{r}
#| output: asis

setFixest_etable(markdown = TRUE, drop = "Constant")
setFixest_dict(dict)

etable(mods, highlight = .("se" = "complaints"))
```

Regression tables

fixest::etable (cont.)

Figures

Figure

Figure

Full-size Figures

You can use the {.background-image} container environment to completely fill the slide background with an image.

Ideally, your figure will be the same aspect ratio as the screen that you’re presenting on.

  • This can be a bit tricky because of the dynamic nature of reveal.js / HTML. But it’s probably something close to 16:9.
  • Aspect ratio can also matter for a regular full-frame images (previous slide).

Interactive plots

Note: Simple flight data example using threejs. There are many interactive plotting options beyond this. (More details.)

Other

Other

What else can the clean theme do?

We have highlighted some theme-specific components in this demo.

But please note that all of the standard reveal.js functionality and plugins are compatible with the clean theme. This includes:

  • chalkboard for annotating slides.
  • multiplex for enabling audience navigation of your slides.
  • pdf printing in case you don’t have access to a web browser.
  • Etc.

Summary

Summary

A minimalist and elegant presentation theme

The Quarto reveal.js clean theme aims to be a minimalist and elegant presention theme. Here are some options to get you started.

Add the theme to an existing project.

quarto install extension grantmcdermott/quarto-revealjs-clean

… or, create a new project using our lean template.

quarto use template grantmcdermott/quarto-revealjs-clean

… or, create a new project using these demo slides as a full template.

quarto use template grantmcdermott/quarto-revealjs-clean-demo

References

Fajgelbaum, Pablo D, Eduardo Morales, Juan Carlos Suarez Serrato, y Owen Zidar. 2018. «State Taxes and Spatial Misallocation», 90.
Hsieh, Chang-Tai, y Enrico Moretti. 2019. «Housing Constraints and Spatial Misallocation». American Economic Journal: Macroeconomics 11 (2): 39.
Moretti, Enrico. 2011. «Local Labor Markets». En Handbook of Labor Economics. Vol. 4. Elsevier.
Suárez Serrato, Juan Carlos, y Owen Zidar. 2016. «Who Benefits from State Corporate Tax Cuts? A Local Labor Markets Approach with Heterogeneous Firms». American Economic Review 106 (9).

Appendix

Tabla 1: Summary of the base R attitude dataset
Unique Missing Pct. Mean SD Min Median Max Histogram
rating 22 0 64.6 12.2 40.0 65.5 85.0
complaints 23 0 66.6 13.3 37.0 65.0 90.0
privileges 24 0 53.1 12.2 30.0 51.5 83.0
learning 23 0 56.4 11.7 34.0 56.5 75.0
raises 21 0 64.6 10.4 43.0 63.5 88.0
critical 21 0 74.8 9.9 49.0 77.5 92.0
advance 20 0 42.9 10.3 25.0 41.0 72.0

Back to main